package com.stedu.service.impl;

import com.stedu.bean.Cars;
import com.stedu.bean.Orders;
import com.stedu.mapper.CarsMapper;
import com.stedu.mapper.OrdersMapper;
import com.stedu.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
   private OrdersMapper ordersMapper;
    @Autowired
    private CarsMapper carsMapper;

    @Override
    public boolean insert(Orders o) {
        Cars cars=carsMapper.selectBycid(o.getCid());
        Date time=new Date();
        o.setOrderstime(time);
        int pirce=  Integer.parseInt(cars.getPirce());
        int days= Integer.parseInt(o.getDays());
        int payint =pirce*days;
        String pay= payint+"";
        o.setPay(pay);
        o.setOstate("1");
      return  ordersMapper.insert(o) == 1 && carsMapper.updateCstate("1", o.getCid())==1;
    }

    @Override
    public boolean update(Orders o) {
        Cars cars=carsMapper.selectBycid(o.getCid());
        cars.setCstate("2");
        carsMapper.update(cars);
        return ordersMapper.update(o)==1;
    }

    @Override
    public Orders selectByOid(int oid) {
        return ordersMapper.selectByOid(oid);
    }

    @Override
    public List<Orders> selectostate(String ostate) {
        return ordersMapper.selectostate(ostate);
    }

    @Override
    public List<Orders> selectId(int id) {
        List<Orders> orders = ordersMapper.selectId(id);
        //计算时间算出状态
        Date date=new Date();
        for (Orders order : orders){
            if (!order.getOstate().equals("3")){
                int days= Integer.parseInt(order.getDays());
                Date orderDate=order.getOrderstime();
                long diffInMillis=date.getTime()-orderDate.getTime();
                long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
                if(diffInDays > days){
                    //已过期
                    order.setOstate("2");
                }else{
                    order.setOstate("1");//进行中
                }
                ordersMapper.update(order);
            }
        }
        return orders;
    }
}
